package com.blog.scheduleTask;

import com.blog.entity.View;
import com.blog.service.BlogService;
import com.blog.service.ViewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Set;

/**
 * @author suoyue_zhan
 * @date 2021/02/04 19:38
 * @descript redis 文章阅读量 持久化到mysql
 */
@Component
@Configuration
@EnableScheduling
public class RedisToMysql {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private BlogService blogService;

    @Autowired
    private ViewService viewService;

    @Scheduled(cron = "59 59 23 * * ?")
//    @Scheduled(cron = "0 0/2 22 * * ?")
    public void blogNumToSQL(){

        ValueOperations<String,Integer> operationNum = redisTemplate.opsForValue();

        //redis读取blog_num类型数据
        int viewTotal = 0;
        Set<String> keys = redisTemplate.keys("blog_num:*");
        for(String key : keys){
            Integer views = operationNum.get(key);
            viewTotal += views;     //日访问总量
            String strId = key.substring(key.lastIndexOf(":")+1,key.length());

            //mysqlg根据strId更新文章阅读量view
            blogService.updateView(Long.parseLong(strId),views);
        }

        //持久化日访问总量
        int view = viewService.insertView(new View(new Date(),viewTotal));

        //redis删除缓存增加的阅读量数据
        redisTemplate.delete(keys);

        //博客文章会缓存阅读量，也需要删缓存
        Set<String> blogDetailKeys = redisTemplate.keys("blog_detail:*");
        redisTemplate.delete(blogDetailKeys);
    }

}
